// ignore_for_file: recursive_getters, library_private_types_in_public_api, unnecessary_null_comparison

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/widgets/sp_button.dart';

import 'city_result.dart';

typedef ResultBlock = void Function(CityResult result);

class CityPickerView extends StatefulWidget {
  // json数据可以从外部传入，如果外部有值，取外部值
  final List? params;
  // 结果返回
  final ResultBlock? onResult;
  const CityPickerView({
    key,
    this.onResult,
    this.params,
  }) : super(key: key);

  @override
  _CityPickerViewState createState() => _CityPickerViewState();
}

class _CityPickerViewState extends State<CityPickerView> {
  List datas = [];
  int provinceIndex = 0;
  int  cityIndex = 0;
  int  areaIndex = 0;

  FixedExtentScrollController? provinceScrollController;
  FixedExtentScrollController? cityScrollController;
  FixedExtentScrollController? areaScrollController;

  CityResult result = CityResult(province:"北京",city: "北京市",area: "东城区");

  bool isShow = false;

  List get provinces {
    if (datas.isNotEmpty) {
      if (provinceIndex == null) {
        provinceIndex = 0;
        result.province = provinces[provinceIndex]['label'];
        result.provinceCode = provinces[provinceIndex]['value'].toString();
      }
      return datas;
    }
    return [];
  }

  List get citys {
    if (provinces.isNotEmpty) {
      return provinces[provinceIndex]['children'] ?? [];
    }
    return [];
  }

  List get areas {
    if (citys.isNotEmpty) {
      if (cityIndex == null) {
        cityIndex = 0;
        result.city = citys[cityIndex]['label'];
        result.cityCode = citys[cityIndex]['value'].toString();
      }
      List list = citys[cityIndex]['children'] ?? [];
      if (list.isNotEmpty) {
        if (areaIndex == null) {
          areaIndex = 0;
          result.area = list[areaIndex]['label'];
          result.areaCode = list[areaIndex]['value'].toString();
        }
      }
      return list;
    }
    return [];
  }

  // 保存选择结果
  _saveInfoData() {
    var prs = provinces;
    var cts = citys;
    var ars = areas;
    if (prs.isNotEmpty) {
      result.province = prs[provinceIndex]['label'];
      result.provinceCode = prs[provinceIndex]['value'].toString();
    } else {
      result.province = '';
      result.provinceCode = '';
    }

    if (cts.isNotEmpty) {
      result.city = cts[cityIndex]['label'];
      result.cityCode = cts[cityIndex]['value'].toString();
    } else {
      result.city = '';
      result.cityCode = '';
    }

    if (ars.isNotEmpty) {
      result.area = ars[areaIndex]['label'];
      result.areaCode = ars[areaIndex]['value'].toString();
    } else {
      result.area = '';
      result.areaCode = '';
    }
  }

  @override
  void dispose() {
    provinceScrollController?.dispose();
    cityScrollController?.dispose();
    areaScrollController?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    //初始化控制器
    provinceScrollController = FixedExtentScrollController();
    cityScrollController = FixedExtentScrollController();
    areaScrollController = FixedExtentScrollController();

    //读取city.json数据
    if (widget.params == null) {
      _loadCitys().then((value) {
        setState(() {
          isShow = true;
        });
      });
    } else {
      datas = widget.params!;
       assert(datas.isNotEmpty);
      setState(() {
        isShow = true;
      });
    }
  }

  Future _loadCitys() async {
    var cityStr =
        await rootBundle.loadString('assets/data.json');
    datas = json.decode(cityStr) as List;
    //result默认取第一组值
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          _firstView(),
          _contentView(),
        ],
      ),
    );
  }

  Widget _firstView() {
    return Container(
      height: 60.w,
      decoration: BoxDecoration(
        border: Border(
            bottom: BorderSide(color: Colors.grey.withOpacity(0.1), width: 1)),
      ),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
              Container(
              margin: EdgeInsets.only(left: 25.w),
              width: 95.w,
              child: SPButton(
                minHeight: 35.w,
                fontSize: 13.sp,
                text: '取消',
                textColor: Colours.app_main_background_color,
                radius: 17.5.w,
                side: const BorderSide(
                  color: Colours.app_main_background_color,
                  width: 1.0,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ),

              Container(
              margin: EdgeInsets.only(right: 25.w),
              width: 95.w,
              child: SPButton(
                minHeight: 35.w,
                fontSize: 13.sp,
                text: "确认",
                textColor: Colours.app_main_color,
                backgroundColor: Colours.app_main_background_color,
                radius: 17.5.w,
                onPressed: () async {
                  Navigator.of(context).pop();
                 if (widget.onResult != null) {
                  widget.onResult!(result);
                }
                },
              ),
            ),
          ]),
    );
  }

  Widget _contentView() {
    return SizedBox(
      height: 300.w,
      child: isShow
          ? Row(
              children: <Widget>[
                Expanded(child: _provincePickerView()),
                Expanded(child: _cityPickerView()),
                Expanded(child: _areaPickerView()),
              ],
            )
          : const Center(
              child: CupertinoActivityIndicator(
                animating: true,
              ),
            ),
    );
  }

  Widget _provincePickerView() {
    return CupertinoPicker(
      scrollController: provinceScrollController,
      onSelectedItemChanged: (index) {
        provinceIndex = index;
        cityIndex = 0;
        if (cityScrollController!.positions.isNotEmpty) {
          cityScrollController?.jumpTo(0);
        }
        areaIndex = 0;
        if (areaScrollController!.positions.isNotEmpty) {
          areaScrollController?.jumpTo(0);
        }
        _saveInfoData();
        setState(() {});
      },
      itemExtent: 36,
      children: provinces.map((item) {
        return Center(
          child: Text(
            item['label'],
            style: const TextStyle(color: Colors.black87, fontSize: 16),
            maxLines: 1,
          ),
        );
      }).toList(),
    );
  }

  Widget _cityPickerView() {
    return Container(
      child: citys.isEmpty
          ? Container()
          : CupertinoPicker(
              scrollController: cityScrollController,
              onSelectedItemChanged: (index) {
                cityIndex = index;
                areaIndex = 0;
                if (areaScrollController!.positions.isNotEmpty) {
                  areaScrollController?.jumpTo(0);
                }
                _saveInfoData();
                setState(() {});
              },
              itemExtent: 36,
              children: citys.map((item) {
                return Center(
                  child: Text(
                    item['label'],
                    style: const TextStyle(color: Colors.black87, fontSize: 16),
                    maxLines: 1,
                  ),
                );
              }).toList(),
            ),
    );
  }

  Widget _areaPickerView() {
    return SizedBox(
      width: double.infinity,
      child: areas.isEmpty
          ? Container()
          : CupertinoPicker(
              scrollController: areaScrollController,
              onSelectedItemChanged: (index) {
                areaIndex = index;
                _saveInfoData();
                setState(() {});
              },
              itemExtent: 36,
              children: areas.map((item) {
                return Center(
                  child: Text(
                    item['label'],
                    style: const TextStyle(color: Colors.black87, fontSize: 16),
                    maxLines: 1,
                  ),
                );
              }).toList(),
            ),
    );
  }
}
